<template>
  <div v-if="top" class="backtop" @click="backTop">
    <i class="ivu-icon ivu-icon-chevron-up"></i>
  </div>
</template>

<script>
export default {
  name: 'backTop',
  data () {
    return {
      top: false
    }
  },
  methods: {
    scrollTop (el, from = 0, to, duration = 500) {
      if (!window.requestAnimationFrame) {
        window.requestAnimationFrame = (
          window.webkitRequestAnimationFrame ||
          window.mozRequestAnimationFrame ||
          window.msRequestAnimationFrame ||
          function (callback) {
            return window.setTimeout(callback, 1000 / 60)
          }
        )
      }
      const difference = Math.abs(from - to)
      const step = Math.ceil(difference / duration * 50)

      function scroll (start, end, step) {
        if (start === end) return

        let d = (start + step > end) ? end : start + step
        if (start > end) {
          d = (start - step < end) ? end : start - step
        }

        if (el === window) {
          window.scrollTo(d, d)
        } else {
          el.scrollTop = d
        }
        window.requestAnimationFrame(() => scroll(d, end, step))
      }
      scroll(from, to, step)
    },
    backTop () {
      this.scrollTop(document.getElementById('app'), document.getElementById('app').scrollTop, 0, 1000)
    },
    handleScroll (ev) {
      if (ev.target.scrollTop > 200) {
        this.top = true
      } else {
        this.top = false
      }
    },
  },
  mounted () {
    document.getElementById('app').addEventListener('scroll', this.handleScroll)
  },
  beforeDestroy () {
    document.getElementById('app').removeEventListener('scroll', this.handleScroll)
  }
}
</script>


<style lang="less" scoped>
  .backtop{
    position: fixed;
    bottom: 100px;
    right: 50px;
    background-color: rgba(0,0,0,.6);
    border-radius: 2px;
    box-shadow: 0 1px 3px rgba(0,0,0,.2);
    transition: all .2s ease-in-out;
    color: #fff;
    font-size: 24px;
    padding: 8px 15px;
    cursor: pointer;
    z-index: 1001;
  }
  .backtop:hover{
    background-color: rgba(0,0,0,.7);
  }
</style>

